package com.xdkj.web.servlet;

import com.xdkj.commons.util.BaseResponse;
import com.xdkj.commons.util.ResponseEnum;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "SystemServlet", urlPatterns = "/system")
public class SystemServlet extends BaseServlet {

    private static final Logger log = LoggerFactory.getLogger(SystemServlet.class);

    /**
     * 登录操作
     *
     * @param request  请求
     * @param response 响应
     * @throws ServletException servlet异常
     * @throws IOException      ioexception
     */
    public BaseResponse login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        log.info("登录操作");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String yzm = request.getParameter("yzm");
        // 先判断验证码
        String kaptcha_session_key = (String) request.getSession().getAttribute("KAPTCHA_SESSION_KEY");
        BaseResponse baseResponse = null;
        if (!yzm.equalsIgnoreCase(kaptcha_session_key)) {
            baseResponse = BaseResponse.error(ResponseEnum.QUERYFAILURE.getCode(), "验证码错误");
            return baseResponse;
        }
        // 用户名密码验证
        // 获取token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //获取主体
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            request.getSession().setAttribute("username", username);
            baseResponse = BaseResponse.ok(ResponseEnum.LOGINGSUCCESS.getCode(), ResponseEnum.LOGINGSUCCESS.getMessage());
        } catch (UnknownAccountException e) {
            baseResponse = BaseResponse.error(ResponseEnum.LOGINGFAILURE.getCode(), "账户不存在");
        } catch (IncorrectCredentialsException e) {
            baseResponse = BaseResponse.error(ResponseEnum.LOGINGFAILURE.getCode(), "密码不正确");
        } catch (LockedAccountException e) {
            baseResponse = BaseResponse.error(ResponseEnum.LOGINGFAILURE.getCode(), "账户被锁定");
        } catch (AuthenticationException e) {
            baseResponse = BaseResponse.error(ResponseEnum.LOGINGFAILURE.getCode(), "登录异常");
        }
        return baseResponse;
    }

    /**
     * 注销 登出
     *
     * @param request  请求
     * @param response 响应
     * @return {@link String}
     * @throws ServletException servlet异常
     */
    public String logout(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login.jsp";
    }

}
